﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using System.Configuration;
using System.Xml;

using System.Threading;
using System.Diagnostics;
using System.Drawing.Imaging;

namespace zhuazhua
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string rootpath = ConfigurationManager.AppSettings["root"].ToString();
        string htmlpath;
        string mobanpath ;
        string temppath;
        private void Form1_Load(object sender, EventArgs e)
        {
            //dm = new ImageLibCS.DrawManager();
            //dm.SetPictureBox(pictureBox1);
            
            mobanpath = rootpath + @"moban\";
            temppath = rootpath + @"temp\";
            DateTime now = DateTime.Now;
            comboBox1.SelectedIndex = 0;
            System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
            //if (checkBox1.Checked)
            //{
            //    this.Width = 550;
            //    this.Height = 550;
            //}
            //else
            //{
            //    this.Width = 185;
            //    this.Height = 160;
            //}
        }
        private string url;
        private string date;
        DateTime dt;
       
        private void button1_Click(object sender, EventArgs e)
        {
            //catches = false;

            if (comboBox1.SelectedIndex < 0)
            {
                MessageBox.Show("未选择来源");
                return; }
            if (dateTimePicker2.Value.Date > DateTime.Now.Date)
            {
                MessageBox.Show("结束时间不能大于今天");
                return;
            }
            if (dateTimePicker3.Value.Date > dateTimePicker2.Value.Date)
            {
                MessageBox.Show("开始时间不能大于结束时间");
                return;
            }
            //button2.Text = "请稍等";
            button1.Enabled = false;
            //button2.Enabled = false;
            //dateTimePicker1.Enabled = false;
            dateTimePicker2.Enabled = false;
            dateTimePicker3.Enabled = false;
            comboBox1.Enabled = false;
            if (catches == false)
            {
                MessageBox.Show("抓取过程很漫长，请耐心等待！");
            }
            date = dateTimePicker3.Value.ToString("yyyyMMdd");
            if (!Directory.Exists(temppath))
            {
                Directory.CreateDirectory(temppath);
            }
            isget = false;
          
            //date = date.Replace("-", "");
            if (comboBox1.SelectedIndex == 0)
            {
                htmlpath = rootpath + @"schtml\";
             
                url = "http://epaper.scol.com.cn/scrb/" + date + "/";
            }
           else if (comboBox1.SelectedIndex == 1)
            {
                htmlpath = rootpath + @"gzhtml\";
                url = "http://www.gzznews.com/gzrb/" + date + "/";
            }
            else
            {
                MessageBox.Show("来源错误");
                return;
            }
            htmlpath = htmlpath + dateTimePicker3.Value.ToString("yyyy-MM/dd/");
            if (!Directory.Exists(htmlpath ))
            {
                Directory.CreateDirectory(htmlpath);
            }
            
            webBrowser1.Navigate(url);
           
               
            
            Thread.Sleep(3000);
        }
        #region
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct INTERNET_CACHE_ENTRY_INFO
        {
            public int dwStructSize;
            public IntPtr lpszSourceUrlName;
            public IntPtr lpszLocalFileName;
            public int CacheEntryType;
            public int dwUseCount;
            public int dwHitRate;
            public int dwSizeLow;
            public int dwSizeHigh;
            public FILETIME LastModifiedTime;
            public FILETIME ExpireTime;
            public FILETIME LastAccessTime;
            public FILETIME LastSyncTime;
            public IntPtr lpHeaderInfo;
            public int dwHeaderInfoSize;
            public IntPtr lpszFileExtension;
            public int dwExemptDelta;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int FileTimeToSystemTime(
        IntPtr lpFileTime,
        IntPtr lpSystemTime);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr FindFirstUrlCacheEntry(
        [MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern,
        IntPtr lpFirstCacheEntryInfo,
        ref int lpdwFirstCacheEntryInfoBufferSize);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool FindNextUrlCacheEntry(
        IntPtr hEnumHandle,
        IntPtr lpNextCacheEntryInfo,
        ref int lpdwNextCacheEntryInfoBufferSize);
        [DllImport("wininet.dll")]
        public static extern bool FindCloseUrlCache(
        IntPtr hEnumHandle);
        const int ERROR_NO_MORE_ITEMS = 259;
        #endregion
        #region FileTimeToSystemTime
        private string FILETIMEtoDataTime(FILETIME time)
        {
            IntPtr filetime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FILETIME)));
            IntPtr systime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SYSTEMTIME)));
            Marshal.StructureToPtr(time, filetime, true);
            FileTimeToSystemTime(filetime, systime);
            SYSTEMTIME st = (SYSTEMTIME)Marshal.PtrToStructure(systime, typeof(SYSTEMTIME));
            string Time = st.wYear.ToString() + "." + st.wMonth.ToString() + "." + st.wDay.ToString() + "." + st.wHour.ToString() + "." + st.wMinute.ToString() + "." + st.wSecond.ToString();
            return Time;
        }
        #endregion

     
        private bool getCFG()
        {
          
           int nNeeded = 0, nBufSize;
           IntPtr buf;
           INTERNET_CACHE_ENTRY_INFO CacheItem;
           IntPtr hEnum;
           bool r;
           FindFirstUrlCacheEntry(null, IntPtr.Zero, ref nNeeded);
           if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
               return false;
           nBufSize = nNeeded;
           buf = Marshal.AllocHGlobal(nBufSize);
           hEnum = FindFirstUrlCacheEntry(null, buf, ref nNeeded);
           while (true)
           {
               CacheItem = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buf,
               typeof(INTERNET_CACHE_ENTRY_INFO));
               string modifiedTime = FILETIMEtoDataTime(CacheItem.LastModifiedTime);
               string expireTime = FILETIMEtoDataTime(CacheItem.ExpireTime);
               string accessTime = FILETIMEtoDataTime(CacheItem.LastAccessTime);
               string syncTime = FILETIMEtoDataTime(CacheItem.LastSyncTime);
               #region 获得数据，存入数据库
               try
               {
                   //此處遍歷CacheItem即可
                   //例如
                   string s2 = Marshal.PtrToStringAuto(CacheItem.lpszSourceUrlName);
                   if (s2.StartsWith(url) && s2.EndsWith(".cfg"))
                   {
                       WebClient web = new WebClient();
                       web.DownloadFile(s2, temppath + "index.xml");
                       return true;
                   }
               }
               catch
               {
                   //異常處理
               }
               #endregion
              
               nNeeded = nBufSize;
               r = FindNextUrlCacheEntry(hEnum, buf, ref nNeeded);
               if (!r && Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
                   break;
               if (!r && nNeeded > nBufSize)
               {
                   nBufSize = nNeeded;
                   buf = Marshal.ReAllocHGlobal(buf, (IntPtr)nBufSize);
                   FindNextUrlCacheEntry(hEnum, buf, ref nNeeded);
               }
           }
           Marshal.FreeHGlobal(buf);
            return false;
        }
        bool isget = false;
        Thread t ;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            catches = true;
            if (isget == false)
            {
                if (getCFG())
                {
                      isget = true;
                    //t=   new Thread(new ThreadStart(zhua));
                    //   t.Start();
                    //zhua();
                      //if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
                      //{
                          backgroundWorker1.RunWorkerAsync();
                      //}
                }
                else
                {
                    ////MessageBox.Show("唉  失败 请重试！");
                    //button1.Enabled = true;
                    ////button2.Enabled = true;
                    ////dateTimePicker1.Enabled = true;
                    //dateTimePicker2.Enabled = true;
                    //dateTimePicker3.Enabled = true;
                    button1_Click(null, null);
                }
            }
        }
        private void zhua()
        {
        
            XmlDocument xml = new XmlDocument();
            string cfgxml = temppath + "index.xml";
            if (!File.Exists(cfgxml))
            {
                MessageBox.Show("索引文件下载失败，请确认已连接上网络并清楚IE缓存后再试");
                return;
            }
           // xml.Load(cfgxml);
            StreamReader sr = new StreamReader(cfgxml);
            string s = sr.ReadToEnd();
            sr.Close();
            while (s.EndsWith("\0"))
            {
                s = s.Replace("\0", "");
            }
            xml.LoadXml(s);
            XmlNode datexml = xml.SelectSingleNode("/PaperInfoFile/PageList");
            if (date != datexml.Attributes["Date"].Value)
            {
                MessageBox.Show("索引文件日期校验失败");
                return;
            }
            XmlNodeList pagelist = xml.SelectNodes("/PaperInfoFile/PageList/Page");//版面
            string pagenumber,pagename,pagexml,pageimage;

            string pagelistmoban = "";
            int k=0;
            foreach (XmlNode list in pagelist)//获取版面列表
            {
                pagenumber = list.Attributes["Number"].Value;
                pagename = list.Attributes["Name"].Value;
              
                string filename = "node_" + pagenumber;
                if (k % 2 == 0)
                {
                    pagelistmoban = pagelistmoban + "<TR><TD class=default align=left>&nbsp;<A id=pageLink href=\"./" + filename + ".htm\">第" + pagenumber + "版：" + pagename + "</A></TD><TD width=55 noWrap align=center><A href=\"/page/\"><IMG border=0 src=\"../../../tplimg/pdf.gif\" width=16 height=16></A></TD></TR>";

                }
                else
                    pagelistmoban = pagelistmoban + "<TR bgColor=#e8e8e8><TD class=default align=left>&nbsp;<A id=pageLink href=\"" + filename + ".htm\">第" + pagenumber + "版：" + pagename + "</A></TD><TD width=55 noWrap align=center><A href=\"/page/\"><IMG border=0 src=\"../../../tplimg/pdf.gif\" width=16 height=16></A></TD></TR>";
                k++;
            }
            pagelistmoban = "<table width='100%' border='0' cellSpacing='0' cellPadding='2'><tbody>" + pagelistmoban + "</tbody></table>";
            //生成所有版面页面模版
            string banmianmoban;
            StreamReader banmiansr = new StreamReader(mobanpath + @"\dyrb\banmian\ban.htm");
            banmianmoban = banmiansr.ReadToEnd();
            banmianmoban = banmianmoban.Replace("[--pagelist--]", pagelistmoban);//版面列表
            banmianmoban = banmianmoban.Replace("[--time--]", dateTimePicker3.Value.ToString("yyyy年MM月dd日"));//日期
            string week = "";
            switch (dt.DayOfWeek)
            {
                case DayOfWeek.Friday:
                    week = "星期五";
                    break;
                case DayOfWeek.Monday:
                    week = "星期一";
                    break;
                case DayOfWeek.Saturday:
                    week = "星期六";
                    break;
                case DayOfWeek.Sunday:
                    week = "星期日";
                    break;
                case DayOfWeek.Thursday:
                    week = "星期四";
                    break;
                case DayOfWeek.Tuesday:
                    week = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    week = "星期三";
                    break;
                default:
                    week = "-";
                        break;
            }
            banmianmoban = banmianmoban.Replace("[--week--]",week);//星期
            

            banmiansr.Close();

            //生成内容页面模版
            string contentmoban;
            StreamReader contentsr = new StreamReader(mobanpath + @"\dyrb\neirong\nei.htm");
            contentmoban = contentsr.ReadToEnd();
            contentsr.Close();
            contentmoban = contentmoban.Replace("[--week--]", week);//星期
            contentmoban = contentmoban.Replace("[--time--]", dateTimePicker3.Value.ToString("yyyy年MM月dd日"));//日期
            for (int i = 0; i < pagelist.Count; i++)
            {
                //生成版面页面

                pagenumber = pagelist[i].Attributes["Number"].Value;
                pagename = pagelist[i].Attributes["Name"].Value;
                pagexml = pagelist[i].Attributes["XML"].Value;
                pageimage = pagelist[i].Attributes["Image"].Value;
                WebClient imagedown = new WebClient();//下载版面图片
                imagedown.DownloadFile(url + pageimage, htmlpath + pageimage);
                GetThumbnail(url + pageimage, url + pageimage, ImageFormat.Jpeg, 355, true);
                xml.LoadXml(xmlstring(pagexml));//获取每个版面的xml
                XmlNodeList ArticleList = xml.SelectNodes("/PageInfoFile/ArticleList/Article");
                string contentlistmoban = "";
               
                string maptem = " <area shape='poly' coords='{0}' href='{1}'>";
                string mapstr = "";
                for (int j = 0; j < ArticleList.Count; j++)
                {
                    //获取每版新闻列表和计算导航地图

                    string IntroTitle = ArticleList[j].SelectSingleNode("IntroTitle").InnerText;
                    string Title = ArticleList[j].SelectSingleNode("Title").InnerText;
                    string SubTitle = ArticleList[j].SelectSingleNode("SubTitle").InnerText;

                    contentlistmoban = contentlistmoban + "<TR><TD class=default vAlign=top><IMG src='../../../tplimg/checkbox.gif' width=10 height=10> </TD><TD class=default vAlign=top><A href='content_" + i.ToString() + j.ToString() + ".htm'><DIV style='DISPLAY: inline' id=mp" + i.ToString() + j.ToString() + ">" + Title + "</DIV></A></TD></TR>";
                    //计算坐标
                    XmlNodeList point = ArticleList[j].SelectNodes("PointList/Point");
                    double beishu = 29.15;
                    string x="", y="";//热点区
                    if (point.Count > 0)
                    {
                        string tmppoint = "";
                        for (int ind = 0; ind < point.Count-1; ind++)
                        {
                            int x1 = Convert.ToInt32(point[ind].Attributes["X"].Value.Trim());
                            int y1 = Convert.ToInt32(point[ind].Attributes["Y"].Value.Trim());
                            //int x3 = Convert.ToInt32(point[2].Attributes["X"].Value.Trim());
                            //int y3 = Convert.ToInt32(point[2].Attributes["Y"].Value.Trim());
                            x = (Math.Abs(Math.Round(x1 / beishu))).ToString();
                            y = (Math.Abs(Math.Round(y1 / beishu))+3).ToString();
                            tmppoint = tmppoint + x + "," + y+",";
                          
                        }
                        mapstr += string.Format(maptem,tmppoint, "content_" + i.ToString() + j.ToString() + ".htm");
                    }
                        //计算坐标结束
                        //if (checkBox1.Checked)
                        //{
                        //    ListViewItem lvi = new ListViewItem();
                        //    lvi.Text = Title;
                        //    lvi.SubItems.Add("-");
                        //    listView1.Items.Add(lvi);
                        //}
                }
                //if (checkBox1.Checked)
                //{
                    //string gtitle = "第{0}版-{1}";
                    //groupBox1.Text = string.Format(gtitle, pagenumber, pagename);
                    //Image img = Bitmap.FromFile(htmlpath + pageimage);
                    //pictureBox1.Image = img;
                    //MessageBox.Show("请在图中采集热点区域！");
                    //button2.Enabled = true;
                    //t.Suspend();
                //}
                contentlistmoban = "<table border='0' cellSpacing='0' cellPadding='1'><tbody>" + contentlistmoban + "</tbody></table>";
                mapstr = "<map id='PagePicMap' name='PagePicMap'>" + mapstr + "</map>";
                string nodeContent = banmianmoban;//生成每个版面页面
                nodeContent = nodeContent.Replace("[--titlelist--]", contentlistmoban);
                nodeContent = nodeContent.Replace("[--pagenum--]", pagenumber);//版面版次
                nodeContent = nodeContent.Replace("[--pagetitle--]", pagename);//版面标题
                nodeContent = nodeContent.Replace("[--pageimage--]", pageimage);//版面图片
                nodeContent = nodeContent.Replace("[--map--]", mapstr);//daohang
                //生成版面内容导航地图
                //nodeContent = creatMap(i, nodeContent);
                string nextnode = "01", prenode = "01";
                if (i < pagelist.Count - 1)
                {
                    nextnode = pagelist[i + 1].Attributes["Number"].Value;
                    nodeContent = nodeContent.Replace("[--nextpage--]", "node_" + nextnode + ".htm");
                }
                else
                {
                    nodeContent = nodeContent.Replace("[--nextpage--]", "#");
                }
                if (i > 0)
                {
                    prenode = pagelist[i - 1].Attributes["Number"].Value;
                    nodeContent = nodeContent.Replace("[--prepage--]", "node_" + prenode + ".htm");
                }
                else
                {
                    nodeContent = nodeContent.Replace("[--prepage--]", "#");
                }
                StreamWriter banmiansw = new StreamWriter(htmlpath + "node_" + pagenumber + ".htm");
                banmiansw.Write(nodeContent);
                banmiansw.Close();//生成版面页面结束

                for (int j = 0; j < ArticleList.Count; j++)//生成内容页面
                {
                    //获取每版新闻内容

                    string IntroTitle = ArticleList[j].SelectSingleNode("IntroTitle").InnerText;
                    string Title = ArticleList[j].SelectSingleNode("Title").InnerText;
                    string SubTitle = ArticleList[j].SelectSingleNode("SubTitle").InnerText;
                    string Author = ArticleList[j].SelectSingleNode("Author").InnerText;
                    string Source = ArticleList[j].SelectSingleNode("Source").InnerText;
                    string Columns = ArticleList[j].SelectSingleNode("Columns").InnerText;
                    string Content = ArticleList[j].SelectSingleNode("Content").InnerText;
                    XmlNodeList ImageList = ArticleList[j].SelectNodes("ImageList/Image");

                    string VideoList = ArticleList[j].SelectSingleNode("VideoList").InnerText;
                    string SoundList = ArticleList[j].SelectSingleNode("SoundList").InnerText;
                    string contentpage = contentmoban;
                    contentpage = contentpage.Replace("[--pagenum--]", pagenumber);
                    contentpage = contentpage.Replace("[--pagetitle--]", pagename);
                    contentpage = contentpage.Replace("[--titlelist--]", contentlistmoban);
                    contentpage = contentpage.Replace("[--title--]", Title);
                    contentpage = contentpage.Replace("[--content--]", Content);
                   // contentpage = creatMap(i, contentpage);
                    contentpage = contentpage.Replace("[--map--]", mapstr);
                    string contentimgs = "";

                    if (ImageList.Count > 0)
                    {
                        foreach (XmlNode img in ImageList)
                        {
                            string imgurl = img.Attributes["Name"].Value;
                            string imgauthor = img.Attributes["Author"].Value;
                            string imgtxt = img.InnerText;
                            if (!string.IsNullOrEmpty(imgurl))
                            {
                                imagedown.DownloadFile(url + imgurl, htmlpath + imgurl);//下载内容图片
                                contentimgs = contentimgs + "<TR><TD><TABLE align=center><TBODY><TR><TD align=center><IMG src='" + imgurl + "'></TD></TR><TR><TD vAlign=middle align=center><P>&nbsp;&nbsp;&nbsp;&nbsp;" + imgtxt + imgauthor + "</P></TD></TR></TBODY></TABLE></TD></TR>";
                            }
                        }
                    }
                    contentpage = contentpage.Replace("[--contentimage--]", contentimgs);
                    string nextcontent = "#", precontent = "#";
                    if (j < ArticleList.Count - 1)
                    {
                        nextcontent = "content_" + i.ToString() + (j + 1).ToString() + ".htm";
                    }
                    contentpage = contentpage.Replace("[--nextcontent--]", nextcontent);
                    if (j > 0)
                    {
                        precontent = "content_" + i.ToString() + (j - 1).ToString() + ".htm";
                    }
                    contentpage = contentpage.Replace("[--precontent--]", precontent);

                    contentpage = contentpage.Replace("[--prepage--]", "node_" + prenode + ".htm");
                    contentpage = contentpage.Replace("[--pageimage--]", pageimage);
                    contentpage = contentpage.Replace("[--nextpage--]", "node_" + nextnode + ".htm");
                    StreamWriter contentsw = new StreamWriter(htmlpath + "content_" + i.ToString() + j.ToString() + ".htm");
                    contentsw.Write(contentpage);
                    contentsw.Close();
                }
            }
                StreamReader indexsr = new StreamReader(rootpath + @"moban\indexmoban.htm");
                string index = indexsr.ReadToEnd();
                indexsr.Close();
                index = index.Replace("[--index--]", "html/" + dateTimePicker3.Value.ToString("yyyy-MM/dd/") + "node_01.htm");
                StreamWriter indexsw = new StreamWriter(rootpath + "index.htm");
                indexsw.Write(index);
                indexsw.Close();
                DirectoryInfo info = new DirectoryInfo(temppath);
            
               info.Delete(true);
               ClearIECache();//清除IE 缓存
               //if (catches)//批量抓取
               //{
               //    isget = false;
               //    //dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1);
               //    if (dateTimePicker1.Value <= dateTimePicker2.Value)
               //    {
               //        dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1);
               //        if (comboBox1.SelectedIndex == 0)
               //        {
               //            htmlpath = rootpath + @"schtml\";
               //            url = "http://epaper.scol.com.cn/scrb/" + date + "/";
               //        }
               //        else if (comboBox1.SelectedIndex == 1)
               //        {
               //            htmlpath = rootpath + @"gzhtml\";
               //            url = "http://www.gzznews.com/gzrb/" + date + "/";
               //        }
               //        htmlpath = htmlpath + dateTimePicker1.Value.ToString("yyyy-MM/dd/");
               //        if (!Directory.Exists(htmlpath))
               //        {
               //            Directory.CreateDirectory(htmlpath);
               //        }
               //        Thread.Sleep(5000);
               //        webBrowser1.Navigate(url);
               //    }
               //}
                button1.Text = "给我抓";
                button1.Enabled = true;
                //dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                dateTimePicker3.Enabled = true;
                //button2.Enabled = true;
                dateTimePicker3.Enabled = true;
                comboBox1.Enabled = true;
              //  MessageBox.Show("抓取完成");
        }

        private bool catches = false;
       // private bool fanish = false;
        private string xmlstring(string filename)
        {
            WebClient webdown = new WebClient();
            webdown.DownloadFile(url+filename, temppath + filename);
            StreamReader sr = new StreamReader(temppath+filename);
            string s = sr.ReadToEnd();
            while (s.EndsWith("\0"))
            {
                s = s.Replace("\0", "");
            }
            sr.Close();
            return s;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            catches = true;
            
            button1_Click(null,null);
        }
        private void ClearIECache()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c " + "del /f /s /q \"%userprofile%\\Local Settings\\Temporary Internet Files\\*.*\"";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            zhua();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //if (catches)//批量抓取
            //{
                dateTimePicker3.Value=dateTimePicker3.Value.AddDays(1);
                if (dateTimePicker3.Value.Date <= dateTimePicker2.Value.Date)
                {
                    //backgroundWorker1.RunWorkerAsync();
                    button1_Click(null, null);
                    //dateTimePicker3.Value = dateTimePicker3.Value.AddDays(1);
                }
            //}
        }
        public bool GetThumbnail(string imgPath, string savePath, ImageFormat format, int scaling, bool keepWidthOrHeight)
        {
            try
            {
                using (Bitmap myBitmap = new Bitmap(imgPath))
                {
                    int width = 0;
                    int height = 0;
                    int tw = myBitmap.Width;//图像的实际宽度
                    int th = myBitmap.Height;//图像的实际高度
                    if (keepWidthOrHeight)//保持宽度
                    {
                        #region 自动保持宽度
                        if (scaling >= tw)
                        {
                            width = tw;
                            height = th;
                        }
                        else
                        {
                            double ti = Convert.ToDouble(tw) / Convert.ToDouble(scaling);
                            if (ti == 0d)
                            {
                                width = tw;
                                height = th;
                            }
                            else
                            {
                                width = scaling;
                                height = Convert.ToInt32(Convert.ToDouble(th) / ti);
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region 自动保持高度
                        if (scaling >= th)
                        {
                            width = tw;
                            height = th;
                        }
                        else
                        {
                            double ti = Convert.ToDouble(th) / Convert.ToDouble(scaling);
                            if (ti == 0d)
                            {
                                width = tw;
                                height = th;
                            }
                            else
                            {
                                width = Convert.ToInt32(Convert.ToDouble(tw) / ti);
                                height = scaling;
                            }
                        }
                        #endregion
                    }
                    using (Image myThumbnail = myBitmap.GetThumbnailImage(width, height, () => { return false; }, IntPtr.Zero))
                    {
                        myThumbnail.Save(savePath, format);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }

        }
    }
}
